package com.army.modules.host.job.listener;

import cn.hutool.core.util.StrUtil;
import com.army.common.utils.BusinessException;
import com.army.modules.batch.entity.ABusiness;
import com.army.modules.batch.mapper.ABusinessMapper;
import com.army.modules.host.entity.HostWater;
import com.army.modules.host.mapper.HostWaterMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
public class FileToDataJobListener extends JobExecutionListenerSupport {
    private final ABusinessMapper aBusinessMapper;
    private final HostWaterMapper hostWaterMapper;

    @Override
    public void afterJob(JobExecution jobExecution) {
        //查询未发送的交易
        QueryWrapper<ABusiness> aw = new QueryWrapper<>();
        aw.eq("trans_result","00");
        List<ABusiness> aBusiness = aBusinessMapper.selectList(aw);
        aBusiness.forEach(a -> {
            QueryWrapper<HostWater> wrapper = new QueryWrapper<>();
            wrapper.eq("global_no",a.getSysWaterNo());
                //查询host系统的交易结果
            HostWater hostWater = hostWaterMapper.selectOne(wrapper);
                if (!Objects.isNull(hostWater)){
                    //校验数据是否为空
                    if (StrUtil.isBlank(hostWater.getTransDate())||StrUtil.isBlank(hostWater.getTransTime())
                    ||StrUtil.isBlank(hostWater.getCoreNo())||StrUtil.isBlank(hostWater.getTransResult())){
                        a.setStatus("03");
                    }else {
                        if ("000000".equals(hostWater.getTransResult())){
                            a.setStatus("01");  //对账结果成功
                        }else {
                            a.setStatus("02"); //对账结果失败
                        }
                    }
                    a.setTransResult("01"); //已对账
                    a.setCoreWaterNo(hostWater.getCoreNo());
                    a.setTransDate(hostWater.getTransDate());
                    a.setTransTime(hostWater.getTransTime());
                    UpdateWrapper<ABusiness> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("sps_no",a.getSysWaterNo());
                    int update = aBusinessMapper.update(a, updateWrapper);
                    if (update!=1){
                        throw new BusinessException("插入异常");
                    }
                }


        });

    }
}
